package main

import (
	"fmt"
	"sync"
	"time"

	goredislib "github.com/go-redis/redis/v8"
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis/goredis/v8"
)

func main() {
	client := goredislib.NewClient(&goredislib.Options{
		Addr:     "120.24.67.46:7379",
		Password: "123456",
	})
	pool := goredis.NewPool(client)
	rs := redsync.New(pool)

	gNum := 2
	mutexName := "my-redlock"
	m := sync.WaitGroup{}

	m.Add(gNum)
	for i := 0; i < gNum; i++ {
		go func() {
			defer m.Done()
			// 锁的名字
			mutex := rs.NewMutex(mutexName)

			fmt.Println("开始获取锁")
			if err := mutex.Lock(); err != nil {
				panic(err)
			}
			fmt.Println("获取成功")

			time.Sleep(time.Second * 8)
			fmt.Println("开始释放锁")

			if ok, err := mutex.Unlock(); !ok || err != nil {
				panic("unlock failed")
			}
			fmt.Println("释放锁成功")
		}()
	}

	m.Wait()
}
